/**
 * @file index.js
 * @author swan
 */
const app = getApp()
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var bdApi = require('../../utils/bdApi.js');
var bdRequest = require('../../utils/bdRequest.js')
import config from '../../utils/config.js'
var pageCount = config.getPageCount;
var WxParse = require('../../wxParse/wxParse.js');
import seoConfig from '../../seoConfig/config.js'
Page({
    data: {
        name: '',
        title: '文章列表',
        postsList: {},
        pagesList: {},
        categoriesList: {},
        postsShowSwiperList: {},
        isLastPage: false,
        page: 1,
        search: '',
        categories: 0,
        categoriesName:'',
        categoriesImage:"", 
        showerror:"none",
        isCategoryPage:"none",
        isSearchPage:"none",
        showallDisplay: "block",
        displaySwiper: "block",
        floatDisplay: "none",
        searchKey:"",
        description:''
    },
    //加载分页
  loadMore: function (e) {
    var self = this;
    if (!self.data.isLastPage) {
      self.setData({
        page: self.data.page + 1
      });
      console.log('当前页' + self.data.page);
      this.fetchPostsData(self.data);
    }
    else {
      swan.showToast({
        title: '没有更多内容',
        mask: false,
        duration: 1000
      });
    }
  },
   formSubmit: function (e) {
        console.log('form发生了submit事件，携带数据为：', e.detail.value);
        let data = e.detail.value
        if (!data.name || !data.tel || !data.school) {
            swan.showToast({
                icon: 'none',
                title: '请填写所有选项',
                duration: 1000
            });
        }
        var url = Api.postFormUrl();
        var ip = new Date().getTime() + Math.round(Math.random() * 10000); // 小程序端无法获取ip
        var content = `类&nbsp;&nbsp;型：毕业证、学位证遗失登记系统\n姓&nbsp;&nbsp;名：${data.name}\n联系电话：${data.tel}\n毕业院校：${data.school}\n来源： 办得爽小程序`
        var postLikeRequest = bdRequest.postRequest(url, { title: "办得爽小程序-毕业证、学位证遗失登记系统", tel: data.tel, name: data.name, content: content, "from": '百度小程序', ip: ip });
        postLikeRequest
            .then(response => {
                if (response.data.status == '200') {
                    swan.showToast({
                        icon: 'success',
                        title: '提交成功'
                    });
                   

                }
            })
    },
  onLoad: function (options) {
    var self = this;
    if (options.categoryID && options.categoryID != 0) {
      self.setData({
        categories: options.categoryID,
        isCategoryPage:"block"
      });
      self.fetchCategoriesData(options.categoryID);
    }else{
        if(options.url && options.url != ''){
            let aa = config.getUrlList.find(resd=>{
                return resd.url==options.url
            })
            if(aa){
               self.setData({
                    categories: aa.categoryID,
                    isCategoryPage:"block"
                });
            }
        }
    }
    if (options.search && options.search != '') {
      swan.setNavigationBarTitle({
        title: "搜索关键字："+options.search,
        success: function (res) {
          // success
        }
      });
      self.setData({
        search: options.search,
        isSearchPage:"block",
        searchKey: options.search
      })

      this.fetchPostsData(self.data);
    }    
  },
  //获取文章列表数据
  fetchPostsData: function (data) {
    var self = this;  
    if (!data) data = {};
    if (!data.page) data.page = 1;
    if (!data.categories) data.categories = 0;
    if (!data.search) data.search = '';
    if (data.page === 1) {
      self.setData({
        postsList: []
      });
    };
    
    swan.showLoading({
      title: '正在加载',
      mask:true
    });

    var getPostsRequest = bdRequest.getRequest(Api.getPosts(data));
    getPostsRequest.then(response =>{
        if (response.statusCode === 200) {
          for (let i = 0; i < response.data.length; i++) {
            var rendered = response.data[i].excerpt.rendered;
            var res = WxParse.bdParse('rendered', 'html', rendered, self, 5, true);
            response.data[i].excerpt.rendered = res;
          }
            if (response.data.length < pageCount) {
                self.setData({
                    isLastPage: true
                });
            };
            self.setData({
                floatDisplay: "block",
                showallDisplay: "block",
                postsList: self.data.postsList.concat(response.data.map(function (item) {
                    var strdate = item.date
                    item.date = util.cutstr(strdate, 10, 1);
                    if(item.categories.length>0){
                        let aa = config.getUrlList.find(resd=>{
                            return resd.categoryID==item.categories[0]
                        })
                        if(aa){
                            item.h5url=aa.url
                        }else{
                            item.h5url=''
                        }
                    }
                    return item;
                })),

            });



        }
        else {
            if (response.data.code == "rest_post_invalid_page_number") {
                self.setData({
                    isLastPage: true
                });

            }
            else {
                swan.showToast({
                    title: response.data.message,
                    duration: 1500
                })
            }
        }   

    })
    .catch(function(){        
        if (data.page == 1) {

            self.setData({
                showerror: "block",
                floatDisplay: "none"
            });

        }
        else {
            swan.showModal({
                title: '加载失败',
                content: '加载数据失败,请重试.',
                showCancel: false,
            });
            self.setData({
                page: data.page - 1
            });
        }
    })
        .finally(function () {
            swan.hideLoading();

        })  
  },  



  // 跳转至查看文章详情
  redictDetail: function (e) {
    // console.log('查看文章');
    var id = e.currentTarget.id,
      url = '../detail/detail?id=' + id;
    swan.navigateTo({
      url: url
    })
  },

  //获取分类列表
  fetchCategoriesData: function (id) {
    var self = this;
    self.setData({
      categoriesList: []
    });

    var getCategoryRequest = bdRequest.getRequest(Api.getCategoryByID(id));

    getCategoryRequest.then(response =>{

        var catImage = "";
        if (typeof (response.data.category_thumbnail_image) == "undefined" || response.data.category_thumbnail_image == "") {
            catImage = "https://www.bds110.com/wp-content/uploads/bdsmp-dacx/website.png";
        }
        else {
            catImage = response.data.category_thumbnail_image;
        }

        self.setData({
            categoriesList: response.data,
            categoriesImage: catImage,
            categoriesName: response.data.name,
             description: response.data.description,

        });

        swan.setNavigationBarTitle({
            title: response.data.name,
            success: function (res) {
                // success
            }
        });
       swan.setPageInfo({
            title: response.data.name + '-办得爽',
            keywords: response.data.name,
            description:response.data.description,
            success: function () {
                console.log('setPageInfo success');
            },
            fail: function (err) {
                console.log('setPageInfo fail', err);
            },
            
       })

        self.fetchPostsData(self.data); 

    })
  },
})
